import axios from 'axios'
import { API_BASE } from './consts'
import { ElMessage } from 'element-plus'

interface ErrorData {
  data?: any
  message: string
  statusCode?: number
}

interface ExtendedError extends Error {
  data?: any
  statusCode?: number
}

const onReject = ({ statusCode, message, data }: ErrorData, showMsg = true) => {
  showMsg && ElMessage.error(message)
  const error = (new Error(message) as ExtendedError)
  error.data = data
  error.statusCode = statusCode
  return Promise.reject(error)
}

const createInstance = (baseURL = API_BASE) => {
  const instance = axios.create()
  instance.defaults.baseURL = baseURL
  instance.defaults.timeout = 10000
  instance.interceptors.response.use(
    res => res.data,
    async e => {
      const res = e.response
      const { data, status } = res || {}
      const message = data?.info ?? e.message ?? '请求失败，请稍候重试'
      const errorData: ErrorData = { message, data, statusCode: status }
      if (status === 403) {
        return onReject(errorData, false)
      }
      return onReject(errorData)
    }
  )
  return instance
}

export const request = createInstance()
